// This file is part of OpenTSDB.
// Copyright (C) 2017 TeleDB Development Group.
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 2.1 of the License, or (at your
// option) any later version.  This program is distributed in the hope that it
// will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser
// General Public License for more details.  You should have received a copy
// of the GNU Lesser General Public License along with this program.  If not,
// see <http://www.gnu.org/licenses/>.
package net.opentsdb.utils;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.Duration;
import java.util.concurrent.*;
import java.util.function.Function;

/**
 *  CompletableFuture支持异步执行
 *  但是并没有支持超时和异常处理，因此在此扩展，提供对CompletableFuture的工具类
 *
 */
public class ExpireFuture {

    private static final Logger log = LoggerFactory.getLogger(ExpireFuture.class);

    private static final ScheduledExecutorService scheduler =
            Executors.newScheduledThreadPool(
                    1,
                    new ThreadFactoryBuilder()
                            .setDaemon(true)
                            .setNameFormat("faildAfter-%d")
                            .build()
            );

    public static <T> CompletableFuture<T> within(CompletableFuture<T> future, Duration duration){

        final CompletableFuture<T> timeout = failAfter(duration);
        return future.applyToEither(timeout, Function.identity());
    }

    public static <T> CompletableFuture<T> failAfter(Duration duration){

        final CompletableFuture<T> promise = new CompletableFuture();
        scheduler.schedule(() -> {
            final TimeoutException ex = new TimeoutException("timeout exception after "+duration);
            return promise.completeExceptionally(ex);
        }, duration.toMillis(), TimeUnit.MILLISECONDS);


        return promise;
    }
}

